package com.duan.execption;


import com.duan.pojo.AppHttpCodeEnum;
import com.duan.pojo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author db
 * @version 1.0
 * @description GlobalExceptionHandler
 * @since 2023/7/23
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 全局异常
    @ExceptionHandler(Exception.class)
    public ResponseResult exceptionHandler(Exception e){
        //打印异常信息
        log.error("出现了异常！ {}",e);
        //从异常对象中获取提示信息封装返回
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),e.getMessage());
    }

    // 自定义异常
    @ExceptionHandler(LxAdminException.class)
    public ResponseResult LxAdminExceptionHandler(LxAdminException e){
        //打印异常信息
        log.error("出现了异常！ {}",e);
        //从异常对象中获取提示信息封装返回
        return ResponseResult.errorResult(e.getCode(),e.getMsg());
    }


    /**
     * 参数非法校验
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        try {
            List<ObjectError> errors = ex.getBindingResult().getAllErrors();
            String message = errors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
            log.error("param illegal: {}", message);
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, message);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.ERROR);
        }
    }


}
